#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
录制文件模型
"""

from sqlalchemy import Column, Integer, String, Enum, Text, DateTime, ForeignKey, BigInteger, Float, Boolean
import json
from sqlalchemy.sql import func
from sqlalchemy.orm import relationship
from app.core.database import Base
import enum

class RecordingStatus(enum.Enum):
    """录制状态枚举"""
    RECORDING = "recording"
    COMPLETED = "completed"
    ERROR = "error"
    PROCESSING = "processing"

class Recording(Base):
    __tablename__ = "recordings"
    
    id = Column(Integer, primary_key=True, index=True)
    name = Column(String(200), nullable=False, comment="录制文件名")
    original_name = Column(String(200), nullable=False, comment="原始文件名")
    
    # 关联信息
    task_id = Column(Integer, ForeignKey("tasks.id"), nullable=False, comment="关联任务ID")
    stream_id = Column(Integer, ForeignKey("streams.id"), nullable=False, comment="关联流ID")
    server_id = Column(Integer, ForeignKey("servers.id"), nullable=True, comment="关联服务器ID")
    
    # 文件信息
    file_path = Column(String(500), nullable=False, comment="文件路径")
    file_size = Column(BigInteger, default=0, comment="文件大小(字节)")
    duration = Column(Float, default=0.0, comment="时长(秒)")
    format = Column(String(50), nullable=True, comment="文件格式")
    
    # 视频信息
    width = Column(Integer, nullable=True, comment="视频宽度")
    height = Column(Integer, nullable=True, comment="视频高度")
    bitrate = Column(Integer, nullable=True, comment="视频码率(bps)")
    fps = Column(Float, nullable=True, comment="帧率")
    
    # 音频信息
    audio_codec = Column(String(50), nullable=True, comment="音频编码")
    audio_bitrate = Column(Integer, nullable=True, comment="音频码率(bps)")
    audio_channels = Column(Integer, nullable=True, comment="音频声道数")
    audio_sample_rate = Column(Integer, nullable=True, comment="音频采样率")
    
    # 状态
    status = Column(Enum(RecordingStatus, values_callable=lambda x: [e.value for e in x]), default=RecordingStatus.RECORDING, comment="状态")
    is_segment = Column(Boolean, default=False, comment="是否为片段")
    parent_id = Column(Integer, ForeignKey("recordings.id"), nullable=True, comment="父录制ID")
    
    # 元数据
    extra_metadata = Column(Text, default="{}", comment="额外元数据 JSON格式")
    
    # 时间戳
    started_at = Column(DateTime(timezone=True), nullable=True, comment="开始时间")
    completed_at = Column(DateTime(timezone=True), nullable=True, comment="完成时间")
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), onupdate=func.now())
    
    # 关系
    task = relationship("Task", backref="recordings")
    stream = relationship("Stream", backref="recordings")
    server = relationship("Server", backref="recordings")
    parent = relationship("Recording", remote_side=[id])
    
    def __repr__(self):
        return f"<Recording(id={self.id}, name={self.name})>"
    
    def to_dict(self):
        try:
            metadata_dict = json.loads(self.extra_metadata) if self.extra_metadata else {}
        except (json.JSONDecodeError, TypeError):
            metadata_dict = {}
        
        return {
            "id": self.id,
            "name": self.name,
            "original_name": self.original_name,
            "task_id": self.task_id,
            "stream_id": self.stream_id,
            "server_id": self.server_id,
            "file_path": self.file_path,
            "file_size": self.file_size,
            "duration": self.duration,
            "format": self.format,
            "width": self.width,
            "height": self.height,
            "bitrate": self.bitrate,
            "fps": self.fps,
            "audio_codec": self.audio_codec,
            "audio_bitrate": self.audio_bitrate,
            "audio_channels": self.audio_channels,
            "audio_sample_rate": self.audio_sample_rate,
            "status": self.status.value,
            "is_segment": self.is_segment,
            "parent_id": self.parent_id,
            "extra_metadata": metadata_dict,
            "started_at": self.started_at.isoformat() if self.started_at else None,
            "completed_at": self.completed_at.isoformat() if self.completed_at else None,
            "created_at": self.created_at.isoformat() if self.created_at else None,
            "updated_at": self.updated_at.isoformat() if self.updated_at else None
        }